package com.rising.face.bytes.P10_滑动窗口.P2_LRU缓存;

import cn.hutool.json.JSONUtil;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2023/1/17 16:41
 */
public class LRUCache<K, V> {
    //负载因子使用默认的0.75
    private final float loadFactory = 0.75f;
    //缓存map
    private LinkedHashMap<K, V> cacheMap;

    public LRUCache(int maxCacheSize) {
        //HashMap达到容量就进行扩容，if ((size >= threshold)，因此需要 +1
        //int capacity = (int)Math.ceil(maxCacheSize / this.loadFactory) + 1;
        cacheMap = new LinkedHashMap<K, V>(maxCacheSize, loadFactory, true) {
            //重写removeEldestEntry，当容量超过maxCacheSize会移除first
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > maxCacheSize;
            }
        };
    }

    public void put(K key, V value) {
        cacheMap.put(key, value);
    }

    public V get(K key) {
        return cacheMap.get(key);
    }

    public static void main(String[] args) {
        LRUCache<Integer, Integer> cache = new LRUCache<>(12);
        for (int i = 1 ; i <= 18; i++) {
            cache.put(i, i);
        }
        System.out.println(JSONUtil.toJsonStr(cache));
        System.out.println(cache.get(6));
        System.out.println(cache.get(9));
    }
}
